package com.sunshine.lnuplus.widget

import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.widget.RemoteViews
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.model.InitData
import com.sunshine.lnuplus.model.WidgetData
import com.sunshine.lnuplus.service.UpdateDayWidgetService
import com.sunshine.lnuplus.ui.activity.SplashActivity
import com.sunshine.lnuplus.utils.DateUtils
import com.sunshine.lnuplus.utils.TagHelper
import es.dmoral.toasty.Toasty


/**
 * 参考
 * https://blog.csdn.net/liliang497/article/details/8308313
 * 感谢！
 */
class DayWidget : AppWidgetProvider(){

    private lateinit var widgetId: SharedPreferences
    private lateinit var edit: SharedPreferences.Editor
    private val REFRESH = "com.sunshine.lnuplus.REFRESH"

    override fun onUpdate(
        context: Context?,
        appWidgetManager: AppWidgetManager?,
        appWidgetIds: IntArray?
    ) {
        super.onUpdate(context, appWidgetManager, appWidgetIds)

        widgetId = context!!.getSharedPreferences("widget_id",Context.MODE_PRIVATE)
        edit = widgetId.edit()

        WidgetData.initData(context)
        WidgetData.initDayView(context)

        val thisWidget = ComponentName(context, DayWidget::class.java)
        val remoteViews = RemoteViews(context.packageName, R.layout.widget_timetable)
        val intent = Intent(context, UpdateDayWidgetService::class.java)

        appWidgetIds?.forEach {
            edit.putInt("$it", it)
            updateWidget(context, appWidgetManager, it, thisWidget, remoteViews, intent)
        }
        edit.apply()
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        super.onReceive(context, intent)
        when(intent?.action){
            REFRESH -> {
                widgetId = context!!.getSharedPreferences("widget_id",Context.MODE_PRIVATE)
//                println(WidgetData.lessonList)
//                println(intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID))
                WidgetData.initData(context)
                WidgetData.initDayView(context)
                widgetId.all.forEach {
                    val appWidgetId = it.value as Int
                    println(appWidgetId)
                    updateWidget(context, AppWidgetManager.getInstance(context), appWidgetId, ComponentName(context, DayWidget::class.java), RemoteViews(context.packageName, R.layout.widget_timetable), intent)
                }

                Toasty.info(context, "可能刷新了，我也没有证据").show()
            }
        }
    }

    override fun onDeleted(context: Context?, appWidgetIds: IntArray?) {
        super.onDeleted(context, appWidgetIds)

        widgetId = context!!.getSharedPreferences("widget_id",Context.MODE_PRIVATE)
        edit = widgetId.edit()
        appWidgetIds?.forEach {
            if(widgetId.contains("$it")){
                edit.remove("$it")
            }
        }
        edit.apply()
    }

    private fun updateWidget(
        context: Context?,
        appWidgetManager: AppWidgetManager?,
        appWidgetId: Int,
        thisWidget: ComponentName,
        remoteViews: RemoteViews,
        intent: Intent
    ) {

        //基本信息
        var textData = "${DateUtils.month}月${DateUtils.day}日 周${DateUtils.getTodayOfWeekString(
            DateUtils.getTodayOfWeek())}"
        if(WidgetData.widgetStyle!!.nextDay && WidgetData.widgetStyle!!.nextDayTime <= DateUtils.hour){
            textData += " 以下是明天课程"
        }
        remoteViews.setTextViewText(R.id.text_date, textData)
        remoteViews.setTextViewText(R.id.text_week, "第${DateUtils.getThisWeek(WidgetData.widgetStyle!!.startMonth, WidgetData.widgetStyle!!.startDay)}周")

        val refreshIntent = Intent(context, DayWidget::class.java).setAction(REFRESH)
        val pendingIntent = PendingIntent.getBroadcast(context, 0, refreshIntent, 0)
        remoteViews.setOnClickPendingIntent(R.id.iv_refresh, pendingIntent)

        //课程
        remoteViews.setRemoteAdapter(R.id.lesson_list_view, intent)
        val intent_start = Intent(context, SplashActivity::class.java)
        //需要在这指明要启动什么，在服务里不行
        val pendingIntentTemplate = PendingIntent.getActivity(context, 1, intent_start, PendingIntent.FLAG_CANCEL_CURRENT)
        remoteViews.setPendingIntentTemplate(R.id.lesson_list_view, pendingIntentTemplate)
        appWidgetManager?.updateAppWidget(thisWidget, remoteViews)
        AppWidgetManager.getInstance(context).notifyAppWidgetViewDataChanged(appWidgetId, R.id.lesson_list_view)
    }

}